from django.http import JsonResponse
from apps.base.models import Rights
from .forms import RightsAddEditForm
from service import res_json_data
from django.views.decorators.http import require_GET
from django.views.decorators.http import require_POST


# /api/v1/rights/treetable/
@require_GET
def get_list_as_treetable(request):
    def get_children(item):
        """递归获取子权限"""
        children = []
        for child in item.rights_set.filter(is_deleted=False):  # 反向查询1:n 查n获取所有
            child_data = child.json()
            child_data['children'] = get_children(child)  # 递归获取子权限
            child_data["children"].sort(key=lambda x: x["sort"])  # 剩下的阶层的排序
            children.append(child_data)
        return children

    first_queryset = Rights.objects.filter(pid__isnull=True, is_deleted=False)  # 权限是自关联的 获取所有一级权限(pid为null的权限)

    res_data = []
    for item in first_queryset:
        item_data = item.json()
        item_data['children'] = get_children(item)
        item_data["children"].sort(key=lambda x: x["sort"])  # 一层排序
        res_data.append(item_data)
    res_data.sort(key=lambda x: x["sort"])  # 顶层排序

    return res_json_data.table_api(data=res_data)


# /api/v1/rights/get_rights_pid_select/
@require_GET
def get_rights_pid_select(request):
    """获取权限的父权限下拉框"""
    rights_info_list = []
    right_queryset = Rights.objects.filter(is_deleted=False)
    for rights_obj in right_queryset:
        if rights_obj.kind != "auth":  # 选择的pid只能是菜单或节点,不能是权限!
            rights_info_list.append(rights_obj.json_tree())  # layui第三方组件combotree拿到该数据后会自动构建树!
    return JsonResponse(rights_info_list, safe=False)


# /api/v1/rights/add/
@require_POST
def rights_add(request):
    form = RightsAddEditForm(request.POST)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)
    title = form.cleaned_data.get('title')
    if Rights.objects.filter(title=title, is_deleted=False).exists():
        msg = '该权限名称已被使用,请重新填写!!'
        return res_json_data.summary_error_api(msg=msg)
    form.save()
    return res_json_data.success_api(msg="权限添加成功!")


# /api/v1/rights/edit/
@require_POST
def rights_edit(request):
    edit_id = request.POST.get('id')
    rights_obj = Rights.objects.filter(id=edit_id, is_deleted=False).first()
    if not rights_obj:
        return res_json_data.not_found_api(msg="权限不存在或已删除!")

    form = RightsAddEditForm(request.POST, instance=rights_obj)
    if not form.is_valid():
        return res_json_data.no_valid_api(form)
    title = form.cleaned_data.get('title')
    if Rights.objects.exclude(id=edit_id).filter(title=title, is_deleted=False).exists():
        msg = '该权限名称已被使用,请重新填写!!'
        return res_json_data.summary_error_api(msg=msg)

    # - 在权限编辑时,同样的要实现"权限禁用启用"的逻辑!!
    current_right_title = str(rights_obj.title)
    is_enabled = form.cleaned_data.get('is_enabled')
    if not is_enabled:  # 想要禁用
        if rights_obj.kind != "auth":
            rights_queryset = rights_obj.rights_set.all()  # 拿到属于它的所有子权限
            for item in rights_queryset:
                if item.is_enabled:
                    return res_json_data.summary_error_api(msg=f"[{current_right_title}] > 它的子权限在使用中,不能禁用!")
    else:  # 想要启用
        if rights_obj.kind == "auth":
            right_father_obj = rights_obj.pid  # 拿到它的父权限对象
            right_father_obj.is_enabled = is_enabled  # 子权限对应的父权限也要启用
            right_father_obj.save()

    form.save()
    return res_json_data.success_api(msg="权限修改成功!")


# /api/v1/rights/del/
@require_POST
def rights_del(request):
    del_id = request.POST.get('id')
    rights_obj = Rights.objects.filter(id=del_id, is_deleted=False).first()
    if not rights_obj:
        return res_json_data.not_found_api(msg="该权限不存在或已删除!")

    # >规则怪谈: 若部门下有子部门,则不能删除
    if rights_obj.rights_set.filter(is_deleted=False):
        return res_json_data.summary_error_api(msg="该权限下有子权限,不能删除!")
    rights_obj.is_deleted = True  # 标记为删除
    rights_obj.save()
    return res_json_data.success_api(msg='权限删除成功!')


# /api/v1/rights/is_enabled/
@require_POST
def rights_is_enabled(request):
    """权限启用/禁用"""
    enabled_id = request.POST.get('id')
    is_enabled = request.POST.get('is_enabled')
    # print(enabled_id, is_enabled, type(is_enabled))
    rights_obj = Rights.objects.filter(id=enabled_id, is_deleted=False).first()
    current_right_title = str(rights_obj.title)
    if not rights_obj:
        return res_json_data.not_found_api(msg=f"{current_right_title}-该权限不存在或已删除!")
    if is_enabled == "0":  # 想要禁用
        if rights_obj.kind != "auth":
            rights_queryset = rights_obj.rights_set.all()  # 拿到属于它的所有子权限
            for item in rights_queryset:
                if item.is_enabled:
                    return res_json_data.summary_error_api(msg=f"[{current_right_title}] > 它的子权限在使用中,不能禁用!")
        rights_obj.is_enabled = is_enabled
        rights_obj.save()
    else:  # 想要启用
        if rights_obj.kind == "auth":
            right_father_obj = rights_obj.pid  # 拿到它的父权限对象
            # print(right_father_obj.title)
            right_father_obj.is_enabled = is_enabled  # 子权限对应的父权限也要启用
            right_father_obj.save()
        rights_obj.is_enabled = is_enabled
        rights_obj.save()
    msg = '权限启用成功!' if int(is_enabled) else '权限禁用成功!'
    return res_json_data.success_api(msg=msg)
